import React, { useEffect, useRef, useState } from 'react';
import { Alert, Button, Form, Input, message, Select, Tooltip } from 'antd';
// import { DownOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout'
import { PlusOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import { addTodo, updateTodoStatus } from '@/services/todo'
import CustomModal from '@/components/CustomModal'
import ProForm, { ProFormText } from '@ant-design/pro-form';

/* const valueEnum = {
  0: 'close',
  1: 'running',
  2: 'online',
  3: 'error',
}; */

export type TableListItem = {
  key: number;
  name: string;
  containers: number;
  creator: string;
  status: string;
  createdAt: number;
  memo: string;
};
// const tableListDataSource: TableListItem[] = [];

// const creators = ['付小小', '曲丽丽', '林东东', '陈帅帅', '兼某某'];

/* for (let i = 0; i < 5; i += 1) {
  tableListDataSource.push({
    key: i,
    name: 'AppName',
    containers: Math.floor(Math.random() * 20),
    creator: creators[Math.floor(Math.random() * creators.length)],
    status: valueEnum[Math.floor(Math.random() * 10) % 4],
    createdAt: Date.now() - Math.floor(Math.random() * 100000),
    memo: i % 2 === 1 ? '很长很长很长很长很长很长很长的文字要展示但是要留下尾巴' : '简短备注文案',
  });
} */

/* const data = [
  { id: 1, title: "列表", status: 0 },
  { id: 2, title: "添加", status: 1 },
  { id: 3, title: "删除", status: 2 },
  { id: 4, title: "修改", status: 1 },
] */

const Todo = ({ dispatch, todos }: any) => {
  const modalRef = useRef(null);
  // let [data, setData] = useState([]);
  useEffect(() => {
    /* dispatch({
      type: "todo/getTodo",
      payload: null,
    }) */
  }, [])

  const changeStatus = async (id: number, status: number) => {
    // console.log('id,status: ', id, status);
    const res = await updateTodoStatus({ id, status });
    // console.log('res: ', res);
    if (res.code === 0) {
      dispatch({
        type: "todo/getTodo",
        payload: null,
      })
      message.success(res.message);
    } else {
      message.error(res.message);
    }
  }

  const handleOnModal = () => {
    // console.log(111, modalRef);
    modalRef.current.showModal();
  }

  const handleSubmit = (values: Object) => {
    // console.log('values: ', values);
    addTodo(values).then(res => {
      // console.log('res: ', res);
      if (res.code === 0) {
        dispatch({
          type: "todo/getTodo",
          payload: null,
        })
        message.success(res.message)
        modalRef.current.handleOk();
      } else {
        message.error(res.message)
      }
    });
  }

  const statuslist = [
    <Alert message="待办" type="info" showIcon />,
    <Alert message="已完成" type="success" showIcon />,
    <Alert message="已取消" type="error" showIcon />,
  ]
  const columns: ProColumns<TableListItem>[] = [
    {
      title: 'ID',
      // width: 80,
      dataIndex: 'id',
      // render: (_) => <a>{_}</a>,
    },
    {
      title: '标题',
      dataIndex: 'title',
      // align: 'right',
      // sorter: (a, b) => a.containers - b.containers,
    },
    {
      title: '状态',
      // width: 80,
      dataIndex: 'status',
      render: (_, { status }) => statuslist[status]

      // initialValue: 'all',
      /* valueEnum: {
        all: { text: '全部', status: 'Default' },
        close: { text: '关闭', status: 'Default' },
        running: { text: '运行中', status: 'Processing' },
        online: { text: '已上线', status: 'Success' },
        error: { text: '异常', status: 'Error' },
      }, */
    },
    {
      title: '修改状态',
      // width: 80,
      // dataIndex: 'modify',
      render: (_, record) => {
        // console.log('record: ', record);
        let editOperation: any = [];
        // @ts-ignore
        if (record.status !== 0) {
          editOperation.push(
            <a
              onClick={() => changeStatus(record.id, 0)}
              style={{ marginRight: '10px' }}
              key={0}
            >
              待办
            </a>
          )
        }
        // @ts-ignore
        if (record.status !== 1) {
          editOperation.push(
            <a
              onClick={() => changeStatus(record.id, 1)}
              style={{ marginRight: '10px' }}
              key={1}
            >
              完成
            </a>
          )
        }
        // @ts-ignore
        if (record.status !== 2) {
          editOperation.push(
            <a
              onClick={() => changeStatus(record.id, 2)}
              style={{ marginRight: '10px' }}
              key={2}
            >
              取消
            </a>
          )
        }

        return editOperation
      }
      /* valueEnum: {
        all: { text: '全部' },
        付小小: { text: '付小小' },
        曲丽丽: { text: '曲丽丽' },
        林东东: { text: '林东东' },
        陈帅帅: { text: '陈帅帅' },
        兼某某: { text: '兼某某' },
      }, */
    },
    /* {
      title: (
        <>
          创建时间
          <Tooltip placement="top" title="这是一段描述">
            <QuestionCircleOutlined style={{ marginLeft: 4 }} />
          </Tooltip>
        </>
      ),
      width: 140,
      key: 'since',
      dataIndex: 'createdAt',
      valueType: 'date',
      sorter: (a, b) => a.createdAt - b.createdAt,
    },
    {
      title: '备注',
      dataIndex: 'memo',
      ellipsis: true,
      copyable: true,
    },
    {
      title: '操作',
      width: 180,
      key: 'option',
      valueType: 'option',
      render: () => [
        <a key="link">链路</a>,
        <a key="link2">报警</a>,
        <a key="link3">监控</a>,
        <TableDropdown
          key="actionGroup"
          menus={[
            { key: 'copy', name: '复制' },
            { key: 'delete', name: '删除' },
          ]}
        />,
      ],
    }, */
  ];

  return (
    <PageContainer>
      <ProTable<TableListItem>
        columns={columns}
        dataSource={todos}
        /* request={(params, sorter, filter) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          console.log(params, sorter, filter);
          return Promise.resolve({
            data: tableListDataSource,
            success: true,
          });
        }} */
        rowKey="id"
        /* pagination={{
          showQuickJumper: true,
        }} */
        search={false}
        dateFormatter="string"
        headerTitle="待办事项列表"
        toolBarRender={() => [
          // <Button key="show">查看日志</Button>,
          // <Button key="out">
          //   导出数据
          //   <DownOutlined />
          // </Button>,
          <Button type="primary" key="primary" onClick={handleOnModal}>
            <PlusOutlined />新建
          </Button>
        ]}
      />

      <CustomModal title="添加待办事项" ref={modalRef} footer={null}>
        <ProForm name="control-hooks" onFinish={(values) => handleSubmit(values)}>
          <ProFormText name="todo" label="待办事项" rules={[{ required: true }]}>
          </ProFormText>
        </ProForm>
      </CustomModal>
    </PageContainer>
  );
};
export default connect(({ todo }: any) => ({ todos: todo.todos }))(Todo)